package main

import (
	"fmt"
	"os"
	"sail/classpath"
	"sail/compile"
	"strings"

	"sail/utils/github.com/go-ffmt/ffmt"
)

var cpOpt = &classpath.CpOption{
	XpathOption:    "cptest/",
	SitePathOption: "cptest/site/",
	UserClassPath:  "cptest/user/",
}

func printPackageEntry(packageEntry *compile.PackageEntry, depth int, useFfmt bool) {
	if useFfmt {
		_, _ = ffmt.P(packageEntry)
		return
	}

	const SPACE = " "

	fmt.Printf("%s%s\n", strings.Repeat(SPACE, depth), packageEntry.EntryName)

	for _, child := range packageEntry.Children {
		printPackageEntry(child, depth+1, useFfmt)
	}

	for _, class := range packageEntry.Classes {
		fmt.Printf("%s.%s  (%s)\n",
			strings.Repeat(SPACE, depth+1), class.ClassName, strings.Join(class.Path, "."))
	}
}

func TestImportMakePackageEntryByPartName(node compile.Node) {
	clsFileNode := node.(*compile.ClassFile)
	impDecls := clsFileNode.Imports

	packageEntry := compile.TestImportMakePackageEntryByPartName(
		impDecls, "sail", 0)

	printPackageEntry(packageEntry, 0, false)
}

func TestMakeEntries(node compile.Node) {
	clsFile := node.(*compile.ClassFile)
	impDecls := clsFile.Imports

	impDecls = compile.TestCleanUpImports(impDecls)

	cp, _ := classpath.GetClasspathByCmdOption(cpOpt)

	_, entries, _ := compile.TestImportMakePackageEntries(
		impDecls, cp)

	for _, e := range entries {
		printPackageEntry(e, 0, false)
	}
}

func TestScopeImport(node compile.Node) {
	clsFileNode := node.(*compile.ClassFile)
	impDecls := clsFileNode.Imports

	scope := new(compile.Scope)

	cp, _ := classpath.GetClasspathByCmdOption(cpOpt)

	compile.TestScopeImport(impDecls, scope, cp)
}

func testImport() {
	fReader, _ := os.Open("./test_sources/test.sail")
	n, ok := compile.TestParser(fReader)

	node := n.(compile.Node)

	if !ok {
		fmt.Println("Compile failed!")
		return
	}

	// TestImportMakePackageEntryByPartName(node)
	// TestScopeImport(node)
	TestMakeEntries(node)
}
